/**
 * User: alesj
 * Date: 2005.1.17
 * Time: 10:57:14
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.generalynx.ecos.data.types;

import org.hibernate.type.Type;
import org.hibernate.Hibernate;

import java.io.Serializable;
import java.util.Set;
import java.util.TreeSet;

public class IntegersCommaDelimited implements Serializable {

    private String m_commaIntegers;
    private int[] m_integers;

    public IntegersCommaDelimited(String commaIntegers) {
        m_commaIntegers = commaIntegers;
        if (commaIntegers != null) {
            String[] integersArray = commaIntegers.split(",");
            m_integers = new int[integersArray.length];
            for (int i = 0; i < integersArray.length; i++) {
                m_integers[i] = Integer.parseInt(integersArray[i].trim());
            }
        }
    }

    public int hashCode() {
        return m_commaIntegers.hashCode();
    }

    public boolean equals(Object obj) {
        IntegersCommaDelimited icdt = (IntegersCommaDelimited)obj;
        return toSet().equals(icdt.toSet());
    }

    public String getSqlValue() {
        return m_commaIntegers;
    }

    public Type getType() {
        return Hibernate.INTEGER;
    }

    public boolean isNull() {
        return (m_integers == null || m_integers.length == 0);
    }

    public Set toSet() {
        Set set = new TreeSet();
        for (int i = 0; m_integers != null && i < m_integers.length; i++) {
            set.add(new Integer(m_integers[i]));
        }
        return set;
    }

    public int getInteger(int index) {
        return m_integers[index];
    }

    public String toString() {
        return getSqlValue();
    }
}
